package com.bmadmin.controller.sms;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.aisino.sms.client.SmsClient;
import com.bmadmin.domain.Datagrid;
import com.bmadmin.domain.MessageDomain;
import com.bmadmin.domain.NormalResult;
import com.bmadmin.domain.SysUsersPOJO;
import com.bmadmin.service.BatchSendService;
import com.bmadmin.service.DelaySendService;
import com.bmadmin.service.SingleSendService;
import com.bmadmin.util.BMUtil;
import com.bmadmin.util.Constants;
import com.bmadmin.util.Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@RestController
@RequestMapping("/batch")
public class batchSendController {
    private Logger logger = LogManager.getLogger(this.getClass().getName());
    @Autowired
    BatchSendService batchSendService;
    @Autowired
    SingleSendService singleSendService;
    @Autowired
    DelaySendService delaySendService;
    
    /**
     * 获取通讯录树
     */
    @GetMapping("/getAddressTree")
    public NormalResult getAddressTree(){
        NormalResult result = new NormalResult();
        result = batchSendService.getAddressTree();
        return result;
    }
    
    /**
     * 新增角色
     */
    @PostMapping("/sendAddress")
    public NormalResult sendAddress(HttpSession session,String ids,String s_message){
    	SysUsersPOJO user = (SysUsersPOJO) session.getAttribute(Constants.USER_INFO_SESSION);
        NormalResult result = new NormalResult();
        if(BMUtil.isNullOrEmpty(ids)){
            result.setCode("9999");
            result.setMsg("未选择通讯录中的联系人！");
            return result;
        }
        if(BMUtil.isNullOrEmpty(s_message)){
            result.setCode("9999");
            result.setMsg("短信内容不可为空！");
            return result;
        }
        try {
	        String[] id = ids.split(",");
	        for(int i=0;i<id.length;i++){
	        	SysUsersPOJO userinfo = batchSendService.getUserInfo(id[i]);
	        	if(userinfo!=null){
	        		MessageDomain message = new MessageDomain();
	        		message.setS_create_id(user.getU_id());
	                message.setS_create_time(BMUtil.getNowTimeForString());
	                message.setS_message(s_message);
	                message.setS_nsrmc(userinfo.getU_name());
	                message.setS_nsrsbh("");
	                message.setS_phone(userinfo.getU_phone());
	                batchSendService.InsertMessageBefore(message);
	        	}
	        }
	        result.setCode("0000");
            result.setMsg("信息提交成功！");
        }catch (Exception e) {
            result.setCode("9999");
            result.setMsg("信息提交异常！");
            logger.error(e);
        }
        return result;
    }

    /**
     * 批量短信发送
     */
    @PostMapping("/sendBeforeMessage")
    public NormalResult sendBeforeMessage(HttpSession session, String JsonStr, String jy_flag,String delay_flag, String s_delaytime) {
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
        SysUsersPOJO user = (SysUsersPOJO) session.getAttribute(Constants.USER_INFO_SESSION);
        NormalResult result = new NormalResult();
        try {
            List<Map> list = Util.jsonToList(JsonStr);
            if (list == null || list.size() == 0) {//未勾选前台列表，默认查出所有该登录人员下面的所有预发送信息
                List<MessageDomain> mlist = batchSendService.findAllBeforeMessage(user.getU_id());
                if (mlist == null || mlist.size() == 0) {
                    result.setCode("9999");
                    result.setMsg("未查询到预发送短信！");
                    return result;
                } else {
                    if (delay_flag.equals("N")) {//立即发送
                        for (MessageDomain message : mlist) {
                            String s_id = message.getS_id();
                            message.setS_id(null);
                            message.setS_state("Y");
                            message.setS_type("1");
                            message.setS_create_time(BMUtil.getNowTimeForString());
                            message.setS_sendtime(BMUtil.getNowTimeForString());
                            if(jy_flag.equals("Y")){
                                message.setS_message("尊敬的【"+message.getS_nsrmc()+"】:"+message.getS_message());
                            }
                            
                            SmsClient smsClient = new SmsClient();
                    		String phones =message.getS_phone();//要发送短信的号码数组
                    		String nr = message.getS_message();//要发送的消息
                    		String id = "1330212";//接入用户ID
                    		String password = "LFGA6B02";//接入用户密码
                    		String sn = Util.getSn();//序列号
                    		String sender = "宁波市杭州湾新区国家税务局";//发送人，预留
                    		String priority = "2";//优先级
                    		String retResult = smsClient.sendMessageMToO(id, password, sn, phones, nr, sender,priority);
//                    		String retResult ="1011";
                    		if(retResult.equals("0")){
                    			logger.info("调用市局短信发送接口返回成功，手机号码【"+phones+"】");
                                //发送成功后，短信保存至短信日志表中
                                singleSendService.InsertMessageLog(message);
                                //删除预发送列表对应的数据
                                batchSendService.deleteBeforeMessage(s_id);
                    		}else{
                    			logger.info("调用市局短信发送接口返回失败，手机号码【"+phones+"】，短信内容【"+nr+"】，返回信息【"+retResult+"】");
                                //如果发送失败，更新预发送表的BZ--发送失败备注
                            	batchSendService.updateBeforeMessageBz(s_id,"市局短信发送接口返回发送失败，手机号码【"+phones+"】，返回信息【"+retResult+"】");//预留的方法
                    		}
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                            	logger.info("休眠失败！");
                            	logger.error(e);
                            }
                        }
                        result.setCode("0000");
                        result.setMsg("批量短信发送成功！");
                    } else {//定时发送
                        for (MessageDomain message : mlist) {
                            String s_id = message.getS_id();
                            message.setS_id(null);
                            message.setS_create_time(BMUtil.getNowTimeForString());
                            message.setS_delaytime(s_delaytime);
                            if(jy_flag.equals("Y")){
                                message.setS_message("尊敬的【"+message.getS_nsrmc()+"】:"+message.getS_message());
                            }
                            //发送成功后，短信保存至短信日志表中
                            delaySendService.InsertMessageDelay(message);
                            //删除预发送列表对应的数据
                            batchSendService.deleteBeforeMessage(s_id);
                        }
                        result.setCode("0000");
                        result.setMsg("批量定时短信发送成功！");
                    }
                }
            } else {//发送勾选的信息
                if (delay_flag.equals("N")) {//立即发送
                    for (Map info : list) {
                        MessageDomain message = new MessageDomain();
                        message.setS_create_id(BMUtil.Object2String(info.get("s_create_id")));
                        if(jy_flag.equals("Y")){
                            message.setS_message("尊敬的【"+BMUtil.Object2String(info.get("s_nsrmc"))+"】:"+BMUtil.Object2String(info.get("s_message")));
                        }else{
                            message.setS_message(BMUtil.Object2String(info.get("s_message")));
                        }
                        message.setS_phone(BMUtil.Object2String(info.get("s_phone")));
                        message.setS_nsrsbh(BMUtil.Object2String(info.get("s_nsrsbh")));
                        message.setS_nsrmc(BMUtil.Object2String(info.get("s_nsrmc")));
                        message.setS_state("Y");
                        message.setS_type("1");
                        message.setS_create_time(BMUtil.getNowTimeForString());
                        message.setS_sendtime(BMUtil.getNowTimeForString());
                        
                        SmsClient smsClient = new SmsClient();
                		String phones =message.getS_phone();//要发送短信的号码数组
                		String nr = message.getS_message();//要发送的消息
                		String id = "1330212";//接入用户ID
                		String password = "LFGA6B02";//接入用户密码
                		String sn = Util.getSn();//序列号
                		String sender = "宁波市杭州湾新区国家税务局";//发送人，预留
                		String priority = "2";//优先级
                		String retResult = smsClient.sendMessageMToO(id, password, sn, phones, nr, sender,priority);
//                		String retResult ="1011";
                		if(retResult.equals("0")){
                			//发送成功后，短信保存至短信日志表中
                            singleSendService.InsertMessageLog(message);
                            //删除预发送列表对应的数据
                            batchSendService.deleteBeforeMessage(BMUtil.Object2String(info.get("s_id")));
                		}else{
                			logger.info("调用市局短信发送接口返回失败，手机号码【"+phones+"】，短信内容【"+nr+"】，返回信息【"+retResult+"】");
                            //如果发送失败，更新预发送表的BZ--发送失败备注
                        	batchSendService.updateBeforeMessageBz(BMUtil.Object2String(info.get("s_id")),"市局短信发送接口返回发送失败，手机号码【"+phones+"】，返回信息【"+retResult+"】");//预留的方法
                		}
                		try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                        	logger.info("休眠失败！");
                        	logger.error(e);
                        }
                    }
                    result.setCode("0000");
                    result.setMsg("批量短信发送成功！");
                } else {//定时发送
                    for (Map info : list) {
                        MessageDomain message = new MessageDomain();
                        message.setS_create_id(BMUtil.Object2String(info.get("s_create_id")));
                        if(jy_flag.equals("Y")){
                            message.setS_message("尊敬的【"+BMUtil.Object2String(info.get("s_nsrmc"))+"】:"+BMUtil.Object2String(info.get("s_message")));
                        }else{
                            message.setS_message(BMUtil.Object2String(info.get("s_message")));
                        }
                        message.setS_phone(BMUtil.Object2String(info.get("s_phone")));
                        message.setS_nsrsbh(BMUtil.Object2String(info.get("s_nsrsbh")));
                        message.setS_nsrmc(BMUtil.Object2String(info.get("s_nsrmc")));
                        message.setS_create_time(BMUtil.getNowTimeForString());
                        message.setS_delaytime(s_delaytime);
                        //定时短信保存至定时表中
                        delaySendService.InsertMessageDelay(message);
                        //删除预发送列表对应的数据
                        batchSendService.deleteBeforeMessage(BMUtil.Object2String(info.get("s_id")));
                    }
                    result.setCode("0000");
                    result.setMsg("批量定时短信发送成功！");
                }
            }
        } catch (Exception e) {
            result.setCode("9999");
            result.setMsg("批量短信发送异常！");
            logger.error(e);
        }
        return result;
    }

    /**
     * 获取待发送列表
     */
    @GetMapping("/getBeforeMessage")
    public Object getBeforeMessage(HttpSession session,Integer page,Integer limit) {
    	Datagrid result = new Datagrid();
        SysUsersPOJO user = (SysUsersPOJO) session.getAttribute(Constants.USER_INFO_SESSION);
        MessageDomain message = new MessageDomain();
        message.setS_create_id(user.getU_id());
        PageHelper.startPage(page, limit);
        List<MessageDomain> list = batchSendService.getBeforeMessageList(message);
		PageInfo pagelist = new PageInfo(list);
		result.setCode(0);
        result.setMsg("success");
        result.setData(list);
        result.setCount(pagelist.getTotal());
        return result;
    }
    
    /**
     * 批量短信删除
     */
    @PostMapping("/deletePlBeforeMessage")
    public NormalResult deletePlBeforeMessage(HttpSession session, String JsonStr) {
        SysUsersPOJO user = (SysUsersPOJO) session.getAttribute(Constants.USER_INFO_SESSION);
        NormalResult result = new NormalResult();
        try {
            List<Map> list = Util.jsonToList(JsonStr);
            if (list == null || list.size() == 0) {
            	result.setCode("9999");
                result.setMsg("未勾选需要删除的记录！");
            } else {
                for (Map info : list) {
                    //删除预发送列表对应的数据
                    batchSendService.deleteBeforeMessage(BMUtil.Object2String(info.get("s_id")));
                }
                result.setCode("0000");
                result.setMsg("批量短信删除成功！");
            }
        } catch (Exception e) {
            result.setCode("9999");
            result.setMsg("批量短信删除异常！");
            logger.error(e);
        }
        return result;
    }

    /**
     * 待发送列表删除
     */
    @PostMapping("/deleteBeforeMessage")
    public NormalResult deleteBeforeMessage(MessageDomain message) {
        NormalResult result = new NormalResult();
        if (BMUtil.isNullOrEmpty(message.getS_id())) {
            result.setCode("9999");
            result.setMsg("预发送传入数据为空!");
            return result;
        }

        result = batchSendService.deleteBeforeMessage(message.getS_id());
        return result;
    }

    @PostMapping(value = "uploadfile")
    public NormalResult uploadfile(
            MultipartFile file,String mblx,
            HttpSession session)
            throws IOException {
        SysUsersPOJO user = (SysUsersPOJO) session.getAttribute(Constants.USER_INFO_SESSION);
        NormalResult result = new NormalResult();
        InputStream is = null;
        try {
            // 判断文件是否为空
            if (file == null) {
                result.setCode("9999");
                result.setMsg("文件不能为空！");
                return result;
            }

            // 获取文件名
            String fileName = file.getOriginalFilename();

            // 验证文件名是否合格
            if (!BMUtil.validateExcel(fileName)) {
                result.setCode("9999");
                result.setMsg("文件必须是excel格式！");
                return result;
            }

            // 进一步判断文件内容是否为空（即判断其大小是否为0或其名称是否为null）
            long size = file.getSize();
            if (StringUtils.isEmpty(fileName) || size == 0) {
                result.setCode("9999");
                result.setMsg("文件内容不能为空！");
                return result;
            }

            is = file.getInputStream();
//			Workbook wb = new XSSFWorkbook(is);
            Workbook wb = WorkbookFactory.create(is);
            // 得到第一个shell
            Sheet sheet = wb.getSheetAt(0);
            // 得到Excel的行数
            int totalRows = sheet.getLastRowNum() + 1 - sheet.getFirstRowNum();
            // 错误信息接收器
            String errorMsg = "";
            String br = "<br/>";
            for (int i = 1; i < totalRows; i++) {
                MessageDomain message = new MessageDomain();
                Row row = sheet.getRow(i);
                if(mblx.equals("1")){
                    String s_nsrsbh = BMUtil.Object2String(row.getCell(1));
                    String s_nsrmc = BMUtil.Object2String(row.getCell(2));
                    if (s_nsrmc.equals("")) {
                        errorMsg += br + "第" + (i + 1) + "行信息接收人为空";
                        continue;
                    }
                    String s_phone = BMUtil.Object2String(row.getCell(3));
                    if (s_phone.equals("")) {
                        errorMsg += br + "第" + (i + 1) + "行手机号码为空";
                        continue;
                    }
                    if(!BMUtil.checkMobileNumber(s_phone)){
                    	errorMsg += br + "第" + (i + 1) + "行手机号码错误";
                        continue;
                    }
                    String s_message = BMUtil.Object2String(row.getCell(4));
                    if (s_message.equals("")) {
                        errorMsg += br + "第" + (i + 1) + "行信息内容为空";
                        continue;
                    }
                    message.setS_create_id(user.getU_id());
                    message.setS_create_time(BMUtil.getNowTimeForString());
                    message.setS_message(s_message);
                    message.setS_nsrmc(s_nsrmc);
                    message.setS_nsrsbh(s_nsrsbh);
                    message.setS_phone(s_phone);
                }else{
                	String s_phone = BMUtil.Object2String(row.getCell(1));
                	if (s_phone.equals("")) {
                        errorMsg += br + "第" + (i + 1) + "行手机号码为空";
                        continue;
                    }
                	String s_nsrsbh = "";
                	String s_nsrmc = BMUtil.Object2String(row.getCell(2));
                	if (s_nsrmc.equals("")) {
                        errorMsg += br + "第" + (i + 1) + "行购方名称为空";
                        continue;
                    }
                    String xfmc = BMUtil.Object2String(row.getCell(3));
                	if (xfmc.equals("")) {
                        errorMsg += br + "第" + (i + 1) + "行销方名称为空";
                        continue;
                    }
                    String kprq = BMUtil.Object2String(row.getCell(4));
                    if (kprq.equals("")) {
                        errorMsg += br + "第" + (i + 1) + "行开票日期为空";
                        continue;
                    }
                    String fpzlmc = BMUtil.Object2String(row.getCell(5));
                    if (fpzlmc.equals("")) {
                        errorMsg += br + "第" + (i + 1) + "行发票种类名称为空";
                        continue;
                    }
                    String fpdm = BMUtil.Object2String(row.getCell(6));
                    if (fpdm.equals("")) {
                        errorMsg += br + "第" + (i + 1) + "行发票代码为空";
                        continue;
                    }
                    String fphm = BMUtil.Object2String(row.getCell(7));
                    if (fphm.equals("")) {
                        errorMsg += br + "第" + (i + 1) + "行发票号码为空";
                        continue;
                    }
                    String spmc = BMUtil.Object2String(row.getCell(8));
                    if (spmc.equals("")) {
                        errorMsg += br + "第" + (i + 1) + "行开票内容为空";
                        continue;
                    }
                    String kpje = BMUtil.Object2String(row.getCell(9));
                    if (kpje.equals("")) {
                        errorMsg += br + "第" + (i + 1) + "行开票金额为空";
                        continue;
                    }
                    if(xfmc.length()>1){
                    	StringBuilder sb = new StringBuilder(xfmc);
                        sb.replace(1, 2, "*");
                        xfmc = sb.toString();
                    }
//                    String s_message = "尊敬的纳税人【"+s_nsrmc+"】您好，您于"+kprq+"在我局代开"+fpzlmc+"一份，具体信息如下：发票代码 "+fpdm+"，发票号码 "+fphm+"，开票内容为"+spmc+"，开票金额 "+kpje+"元【国家税务总局宁波杭州湾新区税务局】。";
                    String s_message = "尊敬的纳税人您好，劳务（服务）提供方【"+xfmc+"】于"+kprq+"在我局代开"+fpzlmc+"一份：发票代码"+fpdm+"，发票号码 "+fphm+"，开票内容为"+spmc+"，开票金额 "+kpje+"元，请您依据《中华人民共和国个人所得税法》相关规定对其履行劳务报酬个人所得税代扣代缴义务【国家税务总局宁波杭州湾新区税务局】";

                    message.setS_create_id(user.getU_id());
                    message.setS_create_time(BMUtil.getNowTimeForString());
                    message.setS_message(s_message);
                    message.setS_nsrmc(s_nsrmc);
                    message.setS_nsrsbh(s_nsrsbh);
                    message.setS_phone(s_phone);
                }
                batchSendService.InsertMessageBefore(message);
            }
            String msg = "文件上传成功！";
            if (!errorMsg.equals("")) {
                msg = errorMsg;
            }
            result.setCode("0000");
            result.setMsg(msg);
            return result;
        } catch (Exception e) {
            result.setCode("9999");
            result.setMsg("文件上传异常！");
            logger.error(e);
            return result;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    is = null;
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 模板下载
     *
     * @param request
     * @param response
     */

    @RequestMapping(value = "/downloadfile")
    public void downloadfile(HttpServletRequest request,
                             HttpServletResponse response) throws IOException {

        //初始一个workbook

        HSSFWorkbook workbook = new HSSFWorkbook();


        // 设置单元格类型
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平布局：居中
        cellStyle.setWrapText(true);

        HSSFSheet sheet = workbook.createSheet();
        // 在sheet中添加表头第0行
        // 用于格式化单元格的数据
        HSSFDataFormat format = workbook.createDataFormat();
        HSSFCellStyle stylecol = workbook.createCellStyle();
        stylecol.setDataFormat(format.getFormat("@"));

//        CellRangeAddress aa = new CellRangeAddress(0, 0, 0, 4);
//        HSSFRow rowthead = sheet.createRow((int) 0);


//        sheet.addMergedRegion(aa);
        HSSFRow row = sheet.createRow((int) 0);
        sheet.autoSizeColumn(1, true);

        HSSFFont font = workbook.createFont();
        HSSFFont fontthead = workbook.createFont();
        // font.setFontName("黑体");
        fontthead.setFontHeightInPoints((short) 16);//设置字体大小
//				font.setFontName("仿宋_GB2312");
        fontthead.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗体显示
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗体显示
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗体显示

        // 创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = workbook.createCellStyle();
        HSSFCellStyle stylethead = workbook.createCellStyle();
        stylethead.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
        stylethead.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
        stylethead.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
        stylethead.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
        stylethead.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框

        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
        stylethead.setFont(fontthead);

//        HSSFCell cellthead = rowthead.createCell(0);
//        cellthead.setCellValue("短信群发信息模板");
//        cellthead.setCellStyle(stylethead);
//
        HSSFCell cell = row.createCell(0);

        cell.setCellValue("序号");
        cell.setCellStyle(style);
        sheet.setDefaultColumnStyle(0, stylecol);

        cell = row.createCell(1);
        cell.setCellValue("纳税人识别号");
        cell.setCellStyle(style);
        sheet.setDefaultColumnStyle(1, stylecol);
        sheet.setColumnWidth(1, (int) (35.7 * 200));

        cell = row.createCell(2);
        cell.setCellValue("纳税人名称");
        cell.setCellStyle(style);
        sheet.setDefaultColumnStyle(2, stylecol);
        sheet.setColumnWidth(2, (int) (35.7 * 200));

        cell = row.createCell(3);
        cell.setCellValue("手机号码");
        cell.setCellStyle(style);
        sheet.setDefaultColumnStyle(3, stylecol);
        sheet.setColumnWidth(3, (int) (35.7 * 200));

        cell = row.createCell(4);
        cell.setCellValue("短信内容");
        cell.setCellStyle(style);
        sheet.setDefaultColumnStyle(4, stylecol);
        sheet.setColumnWidth(4, (int) (35.7 * 600));


        workbook.write(response.getOutputStream());
        String filename = "短信群发信息模板.xls";
        filename = java.net.URLEncoder.encode(filename, "UTF-8");
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename="
                + filename);
        response.addHeader("Content-Length", "");
        OutputStream toClient = new BufferedOutputStream(
                response.getOutputStream());
        response.setContentType("application/octet-stream");


    }
}
